package com.epro.dx.activity.search;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.epro.dx.R;
import com.epro.dx.listenner.HotWordsAsyncTaskListenner;
import com.epro.dx.task.HotWordsAsyncTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.DpPxUtils;
import com.epro.dx.widget.EditTextWithClear;
import com.epro.dx.widget.MyListView;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.content.api.SearchHistoryService;
import com.weipu.common.facade.content.model.SearchHistoryModel;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;

public class SearchActivity extends Activity implements OnClickListener {
	
	private static final int INPUT_SPEED=0;
	private EditTextWithClear searchEditText;
	private LinearLayout hotWordsLayout;
	private ImageView filterSwitch;
	private boolean isFilterSearch;
	private Button clearHistoryBtn;
	private MyListView historyListView;
	private historyAdapter hisAdapter;
	private TextView historyTitle;
	
	private ListView searchRecommendLv;
	
	String[] recommedKeys;
	
	
	private ArrayAdapter<String> searchRecommedadapter;
	// 搜索数据库服务
	private final SearchHistoryService searchHistoryservice = new SearchHistoryService();
	// private List<String> hotWords=new ArrayList<String>();
	private String[] hotWords;
	private ArrayList<SearchHistoryModel> localHistoryList;
	
	private String searchKey;
	
	private String baseHint="";
	
	private String searchHint="";
	
	private LinearLayout contentLayout;
	
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==0){
				if(null!=hotWords){
					searchEditText.setHint(searchHint);
					addHotWordsToLayout();
				}
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_search);
		ActivityUtil.setStatusColor(this, ServerConstant.STATUSCOLOR, null);
		searchKey=getIntent().getStringExtra("searchKey");
		initView();
		setListenner();
		AsyncTaskUtil.executeTask(hotWordsTask);
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		baseHint=getString(R.string.search_hint);
		contentLayout=(LinearLayout) findViewById(R.id.search_content_layout);
		searchRecommendLv=(ListView) findViewById(R.id.search_recommond_lv);
		historyTitle=(TextView) findViewById(R.id.history_title);
		historyListView = (MyListView) findViewById(R.id.search_history_list);
		hotWordsLayout = (LinearLayout) findViewById(R.id.hot_layout);
		addHotWordsToLayout();
		filterSwitch = (ImageView) findViewById(R.id.search_filter_switch);
		clearHistoryBtn = (Button) findViewById(R.id.clear_search_history);
		searchEditText = (EditTextWithClear) findViewById(R.id.edtxt_search);
		searchEditText.isNeedShowClearBtn(true);
		if(!TextUtils.isEmpty(searchKey)){
			searchEditText.setText(searchKey);
		}
		localHistoryList = searchHistoryservice.selectMenusList(this,
				"_id desc");
		hisAdapter = new historyAdapter();
		historyListView.setAdapter(hisAdapter);
		
		searchRecommedadapter=new ArrayAdapter<String>(this,R.layout.search_recommed_item);
		searchRecommendLv.setAdapter(searchRecommedadapter);
	}

	@Override
	protected void onResume() {
		searchEditText.setFocusable(true);
		searchEditText.setFocusableInTouchMode(true);
		searchEditText.requestFocus();
		searchEditText.setSelection(searchEditText.getText().length());
		InputMethodManager im = ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE));
		im.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
		if (localHistoryList.size() <= 0) {
			clearHistoryBtn.setVisibility(View.GONE);
			historyTitle.setVisibility(View.GONE);
		} else {
			clearHistoryBtn.setVisibility(View.VISIBLE);
			historyTitle.setVisibility(View.VISIBLE);
		}
		hisAdapter.notifyDataSetChanged();
		super.onResume();
	}

	/**
	 * 设置过滤开关背景
	 */
	private void setSwitchBg() {
		if (isFilterSearch) {
			filterSwitch.setImageResource(R.drawable.switch_off);
			isFilterSearch = false;
		} else {
			filterSwitch.setImageResource(R.drawable.switch_on);
			isFilterSearch = true;
		}
	}

	/**
	 * 设置控件事件
	 */
	private void setListenner() {
		clearHistoryBtn.setOnClickListener(this);
		filterSwitch.setOnClickListener(this);
		findViewById(R.id.search_btn).setOnClickListener(this);
		findViewById(R.id.search_back).setOnClickListener(this);
		searchEditText.setOnEditorActionListener(new OnEditorActionListener() {
			//
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					searchProListAndSaveSearchKey();
				}
				return false;
			}
		});
		searchEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// 当输入框为空时 隐藏清楚按钮
				searchEditText.setClearIconVisible(!TextUtils
						.isEmpty(searchEditText.getText()));
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
                String text=s.toString();
                if(TextUtils.isEmpty(text)){
                	searchRecommedadapter.clear();
                	searchRecommendLv.setVisibility(View.GONE);
                	contentLayout.setVisibility(View.VISIBLE);
                }else{
                	searchRecommendLv.setVisibility(View.VISIBLE);
                	contentLayout.setVisibility(View.GONE);
                	handler.removeCallbacks(searchRecommendRunabld);
                	handler.postDelayed(searchRecommendRunabld, INPUT_SPEED);
                }
			}
		});

		historyListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				searchEditText
						.setText(localHistoryList.get(position).getName());
				searchEditText.setSelection(searchEditText.getText().length());
				searchProListAndSaveSearchKey();
			}
		});
		
		searchRecommendLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				searchEditText
				.setText(searchRecommedadapter.getItem(position));
				searchEditText.setSelection(searchEditText.getText().length());
				searchProListAndSaveSearchKey();
			}
		});
	}

	/**
	 * 添加热搜词汇到热搜区域
	 */
	private void addHotWordsToLayout() {
		hotWordsLayout.removeAllViews();
		if(null==hotWords){
			return;
		}
		for (int i = 0; i < hotWords.length; i++) {
			final String hotWord = hotWords[i];
			TextView hotWordTv = new TextView(this);
			LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
					getResources().getDimensionPixelSize(R.dimen.size_30));
			params.leftMargin = DpPxUtils.Dp2Px(this, 13);
			int paddingSize = getResources().getDimensionPixelSize(
					R.dimen.size_5);
			hotWordTv.setLayoutParams(params);
			hotWordTv.setGravity(Gravity.CENTER);
			hotWordTv.setPadding(paddingSize, paddingSize, paddingSize,
					paddingSize);
			// hotWordTv.setBackgroundColor(getResources().getColor(R.color.gray));
			hotWordTv.setBackgroundResource(R.drawable.hot_words_bg_tv);
			hotWordTv.setText(hotWord);
			hotWordTv.setTextColor(getResources().getColor(R.color.black));
			hotWordTv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					searchEditText.setText(hotWord);
					searchEditText.setSelection(searchEditText.getText().length());
					 searchProListAndSaveSearchKey();
				}
			});
			hotWordsLayout.addView(hotWordTv);
		}
	}
	
	/**
	 * 请求搜索联动词汇
	 */
	private Runnable searchRecommendRunabld=new Runnable() {
		
		@Override
		public void run() {
			AsyncTaskUtil.executeTask(new SearchRecommedWordTask(searchEditText.getText().toString()));
		}
	};

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.search_btn:
			searchProListAndSaveSearchKey();
			break;
		case R.id.search_filter_switch:
			setSwitchBg();
			break;
		case R.id.clear_search_history:
			clearAllSearchHistory();
			break;
		case R.id.search_back:
			cancelKeyboard(searchEditText);
			finish();
			break;
		default:
			break;
		}
	}

	/**
	 * 删除所有搜索历史
	 */
	private void clearAllSearchHistory() {
		cancelKeyboard(searchEditText);
		if (null != localHistoryList && !localHistoryList.isEmpty()) {
			// 跳出对话框提示是否删除历史记录
			new AlertDialog.Builder(this)
					.setTitle(R.string.confirmation)
					.setCancelable(true)
					.setMessage("Are you sure delete search history?")
					.setPositiveButton(
							R.string.btn_yes,
							new android.content.DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									searchHistoryservice
											.deleteTemplateBySelection(
													getBaseContext(), null,
													null);
									localHistoryList.clear();
									hisAdapter.notifyDataSetChanged();
									clearHistoryBtn.setVisibility(View.GONE);
									historyTitle.setVisibility(View.GONE);
									// myLayout.removeAllViews();
								}
							}).setNegativeButton(R.string.btn_no, null)
					.create().show();
		}
	}

	// 搜索关键词产品并保存关键词
	private void searchProListAndSaveSearchKey() {
		cancelKeyboard(searchEditText);
		final SearchHistoryModel searchHistoryModel = new SearchHistoryModel();
		final String searchKey = searchEditText.getText().toString().trim();

		if (!TextUtils.isEmpty(searchKey)) {
			Intent intent = new Intent(this, SearchListActivity.class);
			intent.putExtra("serchtxt", searchKey);
			intent.putExtra("IsOpenFilter", isFilterSearch);
			searchEditText.setFocusable(false);
			searchEditText.setText(searchKey);
			startActivity(intent);

			AsyncTaskUtil.executeTask(new AsyncTask<Void, Void, String>() {

				@Override
				protected String doInBackground(Void... arg0) {
					for (int i = 0; i < localHistoryList.size(); i++) {
						SearchHistoryModel model = localHistoryList.get(i);
						if (null != model) {
							if (searchKey.equals(model.getName())) {
								localHistoryList.remove(i);
								break;
							}
						}
					}
					searchHistoryModel.setName(searchKey);
					searchHistoryModel.setSearchTime(System.currentTimeMillis());
					localHistoryList.add(0, searchHistoryModel);
					if (localHistoryList.size() > 10) {
						localHistoryList.remove(10);
					}
					searchHistoryservice.deleteTemplateBySelection(
							SearchActivity.this, "historyname=?",
							new String[] { searchKey });
					searchHistoryservice.save(SearchActivity.this,
							searchHistoryModel);
					searchHistoryservice.deleteSearchHistoryNoUsedData();
					return "0";
				}

				@Override
				protected void onPostExecute(String result) {
//					finish();
					super.onPostExecute(result);
				}
			});

		} else {

		}

	}

	/**
	 * 取消键盘
	 * 
	 * @param v
	 *            [参数说明]
	 * @return void [返回类型说明]
	 * @exception throws [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 */
	public void cancelKeyboard(View v) {
		if (null != v) {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
			v.setFocusable(true);
			v.setFocusableInTouchMode(true);
			v.requestFocus();
		}
	}

	private class historyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (null != localHistoryList) {
				return localHistoryList.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			if (null != localHistoryList) {
				localHistoryList.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = View.inflate(SearchActivity.this,
						R.layout.item_search_history, null);
				holder.searchKey = (TextView) convertView
						.findViewById(R.id.search_key);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (null != localHistoryList) {
				SearchHistoryModel shModel = localHistoryList.get(position);
				if (null != shModel) {
					// 设置显示内容
					holder.searchKey.setText(shModel.getName());
				}
			}
			return convertView;
		}

	}

	class ViewHolder {
		TextView searchKey;// 描述信息
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		cancelKeyboard(searchEditText);
		return super.onTouchEvent(event);
	}
	
	/**
	 * 搜索联动数据请求
	 * @author Administrator
	 *
	 */
	private class SearchRecommedWordTask extends AsyncTask<Void, Void, String> {
        String searchStr;
        public SearchRecommedWordTask(String searchKey){
        	this.searchStr=searchKey;
        }
		@Override
		protected void onPreExecute() {
		}

		@Override
		protected String doInBackground(Void... params) {

			try {
				recommedKeys = ProviderFactory.createSearchService()
						.getIntellisenseWords(searchStr);
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			if ("0".equals(result)) {
				if(null!=recommedKeys){
					searchRecommedadapter.clear();
					/**
					 * 遗留问题---数组越界
					 * java.lang.ArrayIndexOutOfBoundsException:
					 */
					int recommedNum = recommedKeys.length > 10 ? 10 : recommedKeys.length;
					if (recommedNum == 0) return;
					//搜索联动最多十条
					for (int i = 0; i < recommedNum; i++) {
						searchRecommedadapter.add(recommedKeys[i]);
					}
//					searchRecommedadapter.addAll(recommedKeys);
					searchRecommedadapter.notifyDataSetChanged();
					
				}
			}
		}
	}
	
	/**
	 * 搜索热搜词汇Task
	 */
	private HotWordsAsyncTask hotWordsTask=new HotWordsAsyncTask(this, new HotWordsAsyncTaskListenner() {
		
		@Override
		public void onPreTask() {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onPostTask(String result, Object obj) {
			hotWords=(String[]) obj;
			if(null!=hotWords){
				addHotWordsToLayout();
				setSearchHint();
			}
		}
		
		@Override
		public void onFinishSomeTask(Object obj) {
			hotWords=(String[]) obj;
			if(null!=hotWords){
				setSearchHint();
				handler.sendEmptyMessage(0);
			}
		}
	});
	
	/**
	 * 设置搜索Hint字符
	 */
	private void setSearchHint(){
		StringBuilder stringHint=new StringBuilder(baseHint);
		if(null==hotWords){
			searchHint=baseHint;
			return;
		}
		for (int i = 0; i < hotWords.length; i++) {
			if(i==0){
				stringHint.append(" "+hotWords[i]);
			}else{
				stringHint.append(",").append(hotWords[i]);
			}
		}
		searchHint=stringHint.toString();
	}
	
}
